﻿using System.Globalization;
using System.Windows.Data;

namespace Super.Hmi.Converters
{
    public abstract class ValueMapperConverter<T> : IValueConverter
    {
        // 正向映射字典 (存储值 -> 显示值)
        protected abstract Dictionary<T, string> ValueToDisplayMap { get; }
        // 反向映射字典 (显示值 -> 存储值)
        protected Dictionary<string, T> DisplayToValueMap => ValueToDisplayMap.ToDictionary(pair => pair.Value, pair => pair.Key);
        // 默认显示值
        protected virtual string DefaultDisplay => "未知";
        // 默认存储值
        protected virtual T DefaultValue => default;
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return null;
            if (value.GetType() == typeof(T))
                return TConverterString(value,targetType,parameter,culture);
            return StringConverterT(value, targetType, parameter, culture);
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value.GetType() == typeof(string))
                return StringConverterT(value, targetType, parameter, culture);
            return TConverterString(value, targetType, parameter, culture);
        }
        private object TConverterString(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null || value == DBNull.Value) return DefaultDisplay;
            try
            {
                var typedValue = (T)System.Convert.ChangeType(value, typeof(T));
                return ValueToDisplayMap.TryGetValue(typedValue, out var display)
                    ? display
                    : DefaultDisplay;
            }
            catch
            {
                return DefaultDisplay;
            }
        }
        private object StringConverterT(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return DefaultValue;
            return DisplayToValueMap.TryGetValue(value.ToString(), out var result)
                ? result
                : DefaultValue;
        }
    }
}
